<?php


namespace api\zmt\controller;


use api\user\model\UserModel;
use api\zmt\model\RegistrationModel;
use api\zmt\validate\registrationValidate;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Qiniu\Auth;
use Qiniu\Http\Error;
use Qiniu\Storage\UploadManager;

class UserController extends RestBaseController
{
    public function index()
    {
        $header = request()->header();
        if (!isset($header['token']) || empty($header['token'])){
            $this->error('缺少 token !');
        }
        // halt(config('app.Jwt_key'));
        $key = new Key(config('app.Jwt_key'),'HS256');
        try{
            $res = JWT::decode($header['token'],$key);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }

        $userInfo = RegistrationModel::field('id,user_name,mobile,image')
            ->where('id',$res->data->user_id)->find();
        $userInfo['image'] =  request()->domain().'/storage/'.$userInfo['image'];
        $this->success('用户信息',$userInfo);
    }

    public function editPost(){

        if (request()->isPost()){
            $header = request()->header();
            if (!isset($header['token']) || empty($header['token'])){
                $this->error('缺少 token !');
            }
            $key = new Key(config('app.Jwt_key'),'HS256');
            try{
                $res = JWT::decode($header['token'],$key);
            }catch (\Exception $exception){
                $this->error($exception->getMessage());
            }
            $data = request()->post();
            $exit = RegistrationModel::find($res->data->user_id);
            $validate = new registrationValidate();
            if (!$validate->scene('edit')->check($data)){
                return error($validate->getError());
            }
            $salt = RandStar();
            $password = $data['password'].$salt;
            $exit->salt = $salt;
            $exit->password =md5($password);
            $exit->user_name = $data['user_name'];
            $exit->image = $data['image'];
            $exit->update_time =time();
            if ( $exit->save()){
                return success('修改信息成功',$exit);
            }else{
                return error('修改信息失败');
            }
        }
    }

    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $mobile = input('mobile');
        $file = request()->file('image');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile( 'image', $file);
        if ($savename){
            $this->success('上传图片成功',[
                'url'=>request()->domain().'/storage/'.$savename]);
        }
    }
    public function qinniu(){
        $file = request()->file('image');
        if (!$file){
            return error('上传失败');
        }
        $accessKey = config('app.qinniuOss.accessKey');
        $secretKey = config('app.qinniuOss.secretKey');
        $bucket = config('app.qinniuOss.bucket');
            // 初始化Auth状态
        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $filePath = $file->getPathname();
        // 上传到存储后保存的文件名
        $key = time().'.'.$file->getOriginalExtension();
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($upToken, $key, $filePath);
        if ($err !== null){
            halt($err->message());
        }else{
            $this->success('上传七牛云成功',[
                'url'=>'http://sejw0hwv8.hd-bkt.clouddn.com/'.$ret['key'],
            ]);
        }

    }

//    public function upload(){
//        // 获取表单上传文件
//        $files = request()->file();
//        try {
//            validate(['image'=>'fileSize:10240|fileExt:jpg|image:200,200,jpg'])
//                ->check($files);
//            $savename = [];
//            foreach($files as $file) {
//                $savename[] = \think\facade\Filesystem::putFile( 'topic', $file);
//            }
//        } catch (\think\exception\ValidateException $e) {
//            echo $e->getMessage();
//        }
//    }
}